package com.yunxin.core.utils.infra.utils;

import jakarta.servlet.http.HttpServletRequest;
import jodd.util.StringPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * @author zero°
 * @since 2023-07-05
 */
@Slf4j
public enum IpUtils {

    /**
     * 实例
     */
    X;

    private static final String UNKNOWN = "unknown";

    private static final String IPV4_DEFAULT_IP = "127.0.0.1";

    private static final String IPV6_DEFAULT_IP = "0:0:0:0:0:0:0:1";

    /**
     * 获取IP地址
     * <p>
     * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址
     * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
     */
    public String getIpAddr(HttpServletRequest request) {
        String ip = "";
        if (Objects.isNull(request)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (org.apache.commons.lang3.StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (org.apache.commons.lang3.StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (org.apache.commons.lang3.StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if (ip != null && ip.indexOf(",") >0) {
            String[] parts = ip.split(StringPool.COMMA);
            for (String part : parts) {
                if (!part.isEmpty() && ! UNKNOWN.equalsIgnoreCase(part)) {
                    ip = part.trim();
                    break;
                }
            }
        }
        if (StringUtils.isBlank(ip) || IPV6_DEFAULT_IP.equals(ip)) {
            ip = IPV4_DEFAULT_IP;
        }
        return ip;
    }

}
